package it.bit.jlightqueryer.bl;

import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Class to group the data of a resultset and the headers
 * @author PerezDeQueya80
 */
public class ResultSetResult {
	public String[] headers;
	public List[] data;

	/**
	 * Initialize headers and data with a ResultSetMetaData
	 * @param rsmd
	 * @throws SQLException
	 */
	public void initMetaData(ResultSetMetaData rsmd) throws SQLException {
		int colCount = rsmd.getColumnCount();
		headers = new String[colCount];
		data = new ArrayList[colCount];
		for (int i = 0; i < headers.length; i++) {
			headers[i] = rsmd.getColumnLabel(i+1);
			data[i] = new ArrayList();
		}
	}

	/**
	 * This method is used to give comprensive Object to table
	 * @param column
	 * @param row
	 * @return a cell as String
	 */
	public Object getObject(int col, int row) {
		String result = null;
		Object o = data[col].get(row);
		if (o != null) {
			if (o instanceof Date) {
				Date date = (Date) o;
				Calendar c = Calendar.getInstance();
				c.setTime(date);
				result = c.get(Calendar.DAY_OF_MONTH) +
					"/" +
					(c.get(Calendar.MONTH)+1) +
					"/" +
					c.get(Calendar.YEAR) +
					" " +
					c.get(Calendar.HOUR_OF_DAY) +
					":" +
					c.get(Calendar.MINUTE) +
					":" +
					c.get(Calendar.SECOND) +
					"." +
					c.get(Calendar.MILLISECOND);
			}
			else {
				return o;
			}
		}
		return result;
	}

	/**
	 * Return all data as Object[][], to make easier jtable integration
	 * @return all data as Object[][]
	 */
	public Object[][] getDataAsArrays() {
		Object[][] result = new Object[0][0];
		if (data.length>0) {
			result = new Object[data[0].size()][data.length];
			for (int i = 0; i < result.length; i++) {
				for (int j = 0; j < result[i].length; j++) {
					result[i][j] = getObject(j, i);//data[j].get(i);
				}
			}
		}
		return result;
	}
}
